package components;

import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JTextField;

public class TextFieldVerifier extends CustomVerifier {

    public TextFieldVerifier(String message, JComponent component) {
        super(message, component);
    }

    @Override
    public boolean verify(JComponent input) {
        boolean ret = true;
        if (input instanceof JTextField) {
            JTextField tf = (JTextField) input;
            ret = tf.getText() != null && tf.getText().trim().length() != 0 && !hasSpecialCharacters(tf.getText());
        }
        return ret;
    }
    
    private boolean hasSpecialCharacters(String s) {
        return !s.matches("\\w+");
    }

    @Override
    public boolean shouldYieldFocus(JComponent input) {
        boolean valueOK;
        
        if (input.isEnabled()) {
            //If the component is enabled, validate the data
            valueOK = verify(input);

            if (input instanceof JTextField) {
                JTextField field = (JTextField) input;
                if (!valueOK) {
                    field.setBorder(BorderFactory.createLineBorder(Color.red));
                    field.selectAll();
                } else {
                    input.setBorder(null);
                    input.updateUI();
                }
            }
        } else {
            //If it's not enabled, simply return true.
            valueOK = true;
        }
        
        return valueOK;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        shouldYieldFocus(component);
    }
    
}
